package com.miwzn.boot.modules.sys.web;

import com.miwzn.base.AbstractController;
import com.miwzn.boot.modules.sys.entity.dto.SysUserRoleRelDto;
import com.miwzn.boot.modules.sys.entity.po.SysUserRoleRel;
import com.miwzn.boot.modules.sys.entity.qm.SysUserRoleRelQuery;
import com.miwzn.boot.modules.sys.service.SysUserRoleRelService;
import com.miwzn.comm.ResponseEntity;
import com.miwzn.comm.annotation.OperationLog;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: wzn
 * @Date: 2018-12-27 14:45:47
 * @Description: www.miwzn.com mvc api
 */
@ResponseBody
@Controller
@RequestMapping("sys/user/role/rel")
public class SysUserRoleRelController extends AbstractController<SysUserRoleRel, SysUserRoleRelDto, SysUserRoleRelQuery> {
    private static Logger logger = LoggerFactory.getLogger(SysUserRoleRelController.class);

    @Autowired
    private SysUserRoleRelService sysUserRoleRelService;

    /**
     * 列表
     *
     * @param entity
     *
     * @return
     */
    @OperationLog(operation = "系统-用户-角色",content ="获取用户-角色列表")
    @RequiresPermissions("sys:user:role:rel:list")
    @GetMapping("/list")
    public ResponseEntity list(SysUserRoleRelQuery entity) {
        return super.listD(entity);
    }

    /**
     * 添加
     *
     * @param entity
     *
     * @return
     */
    @OperationLog(operation = "系统-用户-角色",content ="分配用户-角色")
    @RequiresPermissions("sys:user:role:rel:adds")
    @PostMapping("adds")
    public ResponseEntity adds(@RequestBody List<SysUserRoleRelDto> entity) {
        del(entity);
        return del(entity) ? super.adds(entity) : ResponseEntity.success("保存成功");
    }

    private boolean del(List<SysUserRoleRelDto> entity) {
        if (CollectionUtils.isNotEmpty(entity)) {
            SysUserRoleRel sysUserRoleRel = new SysUserRoleRel();
            sysUserRoleRel.setUserId(entity.get(0).getUserId());
            sysUserRoleRelService.delete(sysUserRoleRel);
        }
        if (CollectionUtils.isEmpty(entity) || (CollectionUtils.isNotEmpty(entity) && entity.size() == 1 && entity.get(0).getRoleId() == null)) {
            return false;
        } else {
            return true;
        }
    }
}
